package com.glory.wxelectricitypda.activity;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.FixtureBeanDataAdapter;
import com.glory.wxelectricitypda.adapter.MaterielDataAdapter;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.EqpEntoty;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.FreeApi_DialogUtils;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;

public class MaterielUpActivity extends BaseDialogActivity {


    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.flPosition)
    FrameLayout flPosition;
    @BindView(R.id.tvPosition)
    TextView tvPosition;
    @BindView(R.id.ivPosition)
    ImageView ivPosition;
    @BindView(R.id.etMTid)
    FreeUI_ClearEditText etMTid;
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.rbMaterial)
    RadioButton rbMaterial;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.rvFixtureList)
    RecyclerView rvFixtureList;
    @BindView(R.id.rvMaterielText)
    LinearLayout rvMaterielText;
    @BindView(R.id.rvMaterielLinear)
    LinearLayout rvMaterielLinear;
    @BindView(R.id.rvFixtureText)
    LinearLayout rvFixtureText;
    @BindView(R.id.rvFixtureLinear)
    LinearLayout rvFixtureLinear;

    private FreeUI_GeneralPop mPositionPop;
    private ArrayList<String> positionNameList = new ArrayList<>();
    private ArrayList<String> positionDescList = new ArrayList<>();
    private MaterielDataAdapter mMaterielDataAdapter;
    private FixtureBeanDataAdapter mFixtureBeanDataAdapter;
    private FreeUI_GeneralFragmentDialog freeUI_generalFragmentDialog;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_materiel_up;
    }

    @Override
    protected void initView() {

        freeUI_titleView.setTitle("物料治具上/下机");
        freeUI_titleView.setRightListener("上机", new View.OnClickListener() {
            @Override
            public void onClick(View s) {
                materielUp();
            }
        });

        rvMaterielList.setLayoutManager(new LinearLayoutManager(this));
        rvMaterielList.setItemAnimator(new DefaultItemAnimator());
        rvMaterielList.addItemDecoration(new DividerItemDecoration(this, 1));

        rvFixtureList.setLayoutManager(new LinearLayoutManager(this));
        rvFixtureList.setItemAnimator(new DefaultItemAnimator());
        rvFixtureList.addItemDecoration(new DividerItemDecoration(this, 1));

        mMaterielDataAdapter = new MaterielDataAdapter(null);
        mMaterielDataAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mMaterielDataAdapter.isFirstOnly(true);

        mFixtureBeanDataAdapter = new FixtureBeanDataAdapter(null);
        mFixtureBeanDataAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mFixtureBeanDataAdapter.isFirstOnly(true);

        rvMaterielList.setAdapter(mMaterielDataAdapter);
        rvFixtureList.setAdapter(mFixtureBeanDataAdapter);

        mMaterielDataAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if (etEqpId.getText().toString().equals("")) {
                    showToast("请扫描设备编号", false);
                    return;
                }
                if (mMaterielDataAdapter.getData().get(i).getMATERIALTYPE().equals("WAFER")) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("EqpID", etEqpId.getText().toString());
                        jsonObject.put("Position", mMaterielDataAdapter.getData().get(i).getPOSITION());
                        jsonObject.put("Type", mMaterielDataAdapter.getData().get(i).getMATERIALTYPE());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    NetUtils.requestPostUtils("getMTConsume", "GetMTConsume", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<EqpEntoty>>(
                            new TypeToken<ResponseBean<EqpEntoty>>() {
                            }.getType(), getSupportFragmentManager(), this) {
                        @Override
                        public void onSuccess(Response<ResponseBean<EqpEntoty>> response) {
                            if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                                editValue(mMaterielDataAdapter.getData().get(i).getPOSITION(),"M",mMaterielDataAdapter.getData().get(i).getMLOTID(),mMaterielDataAdapter.getData().get(i).getMATERIALTYPE(),String.valueOf(response.body().getBody().getValue()));
                            }
                        }

                        @Override
                        public void onError(Response<ResponseBean<EqpEntoty>> response) {
                            super.onError(response);
                            loadError(response.getException(), "GetMTConsume");
                        }
                    });
                } else {
                    FreeApi_DialogUtils.getConfirmAndCancelDialog(MaterielUpActivity.this, "是否确认下机?", new FreeUI_CommonCallback() {
                        @Override
                        public void onSuccess() {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("EqpID", etEqpId.getText().toString());
//                    jsonObject.put("LotID", etLotId.getText().toString());
                                jsonObject.put("Position", mMaterielDataAdapter.getData().get(i).getPOSITION());
                                jsonObject.put("MTType", "M");
                                jsonObject.put("MTID", mMaterielDataAdapter.getData().get(i).getMLOTID());
                                jsonObject.put("Type", mMaterielDataAdapter.getData().get(i).getMATERIALTYPE());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            NetUtils.requestPostUtils("mtKittingDeassign", "MTKittingDeassign", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<Object>>(
                                    new TypeToken<ResponseBean<Object>>() {
                                    }.getType(), getSupportFragmentManager(), this) {
                                @Override
                                public void onSuccess(Response<ResponseBean<Object>> response) {
                                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                                        showToast("下机成功", true);
                                        getEqpKitting(etEqpId.getText().toString());
                                    }
                                }

                                @Override
                                public void onError(Response<ResponseBean<Object>> response) {
                                    super.onError(response);
                                    loadError(response.getException(), "MTKittingDeassign");
                                }
                            });
                        }
                    }, () -> {
                    }).show(getSupportFragmentManager(), "DELETE_DIALOG");
                }
            }
        });

        mFixtureBeanDataAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int i) {

                if (etEqpId.getText().toString().equals("")) {
                    showToast("请扫描设备编号", false);
                    return;
                }
                if (mFixtureBeanDataAdapter.getData().get(i).getMATERIALTYPE().equals("WAFER")) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("EqpID", etEqpId.getText().toString());
                        jsonObject.put("Position", mFixtureBeanDataAdapter.getData().get(i).getPOSITION());
                        jsonObject.put("Type", mFixtureBeanDataAdapter.getData().get(i).getMATERIALTYPE());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    NetUtils.requestPostUtils("getMTConsume", "GetMTConsume", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<EqpEntoty>>(
                            new TypeToken<ResponseBean<EqpEntoty>>() {
                            }.getType(), getSupportFragmentManager(), this) {
                        @Override
                        public void onSuccess(Response<ResponseBean<EqpEntoty>> response) {
                            if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                                editValue(mFixtureBeanDataAdapter.getData().get(i).getPOSITION(),"T",mFixtureBeanDataAdapter.getData().get(i).getMLOTID(),mFixtureBeanDataAdapter.getData().get(i).getMATERIALTYPE(),String.valueOf(response.body().getBody().getValue()));
                            }
                        }

                        @Override
                        public void onError(Response<ResponseBean<EqpEntoty>> response) {
                            super.onError(response);
                            loadError(response.getException(), "GetMTConsume");
                        }
                    });
                } else {
                    FreeApi_DialogUtils.getConfirmAndCancelDialog(MaterielUpActivity.this, "是否确认下机?", new FreeUI_CommonCallback() {
                        @Override
                        public void onSuccess() {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("EqpID", etEqpId.getText().toString());
//                    jsonObject.put("LotID", etLotId.getText().toString());
                                jsonObject.put("Position", mFixtureBeanDataAdapter.getData().get(i).getPOSITION());
                                jsonObject.put("MTType", "T");
                                jsonObject.put("MTID", mFixtureBeanDataAdapter.getData().get(i).getMLOTID());
                                jsonObject.put("Type", mFixtureBeanDataAdapter.getData().get(i).getMATERIALTYPE());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            NetUtils.requestPostUtils("mtKittingDeassign", "MTKittingDeassign", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<Object>>(
                                    new TypeToken<ResponseBean<Object>>() {
                                    }.getType(), getSupportFragmentManager(), this) {
                                @Override
                                public void onSuccess(Response<ResponseBean<Object>> response) {
                                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                                        showToast("下机成功", true);
                                        getEqpKitting(etEqpId.getText().toString());
                                    }
                                }

                                @Override
                                public void onError(Response<ResponseBean<Object>> response) {
                                    super.onError(response);
                                    loadError(response.getException(), "MTKittingDeassign");
                                }
                            });
                        }
                    }, () -> {
                    }).show(getSupportFragmentManager(), "DELETE_DIALOG");
                }
            }
        });
    }

    private void editValue(String position, String type, String mlotid, String materialtype,String edit) {
        freeUI_generalFragmentDialog = FreeApi_DialogUtils.getScanDialog(MaterielUpActivity.this, "请输入物料/治具消耗",edit, new FreeUI_TextCallback() {
            @Override
            public void onSuccess(String s) {
                if (s.equals("")){
                    showToast("请输入物料/治具消耗",false);
                    return;
                }
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("EqpID", etEqpId.getText().toString());
                    jsonObject.put("Position", position);
                    jsonObject.put("MTType", type);
                    jsonObject.put("MTID", mlotid);
                    jsonObject.put("Type", materialtype);
                    jsonObject.put("Qty", s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                NetUtils.requestPostUtils("mtKittingDeassign", "MTKittingDeassign", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<Object>>(
                        new TypeToken<ResponseBean<Object>>() {
                        }.getType(), getSupportFragmentManager(), this) {
                    @Override
                    public void onSuccess(Response<ResponseBean<Object>> response) {
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            showToast("下机成功", true);
                            getEqpKitting(etEqpId.getText().toString());
                        }
                    }

                    @Override
                    public void onError(Response<ResponseBean<Object>> response) {
                        super.onError(response);
                        loadError(response.getException(), "MTKittingDeassign");
                    }
                });
            }
        });
        freeUI_generalFragmentDialog.show(getSupportFragmentManager(), "PASSWORD_VERIFY");
    }


    @Override
    protected void initData() {

        etEqpId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    positionNameList.clear();
                    positionDescList.clear();
                    mMaterielDataAdapter.setNewData(null);
                    mFixtureBeanDataAdapter.setNewData(null);
                    requestEqpInfo(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        initEdit(etMTid, s -> {
            tvType.setText("");
            JSONObject jsonObject = new JSONObject();
            try {
                if (s.contains("|")) {
                    s = s.replace("|", ",").split(",")[2];
                }
                jsonObject.put("MTID", s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            etMTid.setText(s);
            NetUtils.requestPostUtils("getMTInfo", "GetMTInfo", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<EqpEntoty>>(
                    new TypeToken<ResponseBean<EqpEntoty>>() {
                    }.getType(), getSupportFragmentManager(), this) {
                @Override
                public void onSuccess(Response<ResponseBean<EqpEntoty>> response) {
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        if (response.body().getBody().getXMLot() != null && response.body().getBody().getXTool() == null){
                            if (rbMaterial.isChecked()){
                                tvType.setText(response.body().getBody().getXMLot().getMATERIALTYPE());
                            }else {
                                showToast("当前扫描治具，请选择物料", false);
                                etMTid.setText("");
                                etMTid.requestFocus();
                            }
                        }
                        if (response.body().getBody().getXMLot() == null && response.body().getBody().getXTool() != null){
                            if (rbMaterial.isChecked()){
                                showToast("当前扫描物料，请选择治具", false);
                                etMTid.setText("");
                                etMTid.requestFocus();
                            }else {
                                tvType.setText(response.body().getBody().getXTool().getMATERIALTYPE());
                            }
                        }

                    }
                }

                @Override
                public void onError(Response<ResponseBean<EqpEntoty>> response) {
                    super.onError(response);
                    loadError(response.getException(), "GetMTInfo");
                }
            });
        });


        flPosition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPositionPop != null) {
                    if (mPositionPop.isShowing()) {
                        mPositionPop.dismiss();
                    }
                } else {
                    mPositionPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPosition.getWidth(), positionDescList, ivPosition, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvPosition.setText(s);
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivPosition);
                mPositionPop.showAsDropDown(flPosition, 0, 0);
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    private void requestEqpInfo(final String eqpID) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("EqpID", eqpID);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostUtils("getKittingPosition", "GetKittingPosition", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<EqpEntoty>>(
                new TypeToken<ResponseBean<EqpEntoty>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<EqpEntoty>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (EqpEntoty.positionsetlineBean positionsetline : response.body().getBody().getXPOSITIONSET().getPOSITIONSETLINES()) {
                        positionNameList.add(positionsetline.getPOSITIONNAME());
                        positionDescList.add(positionsetline.getPOSITIONDESC());
                    }

                    getEqpKitting(eqpID);
                }
            }

            @Override
            public void onError(Response<ResponseBean<EqpEntoty>> response) {
                super.onError(response);
                loadError(response.getException(), "GetKittingPosition");
            }
        });
    }

    private void getEqpKitting(String eqpID) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("EqpID", eqpID);
            jsonObject.put("ChargType", rbMaterial.isChecked()?"MLOT":"TOOL");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostUtils("getEqpKitting", "GetEqpKitting", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<EqpEntoty>>(
                new TypeToken<ResponseBean<EqpEntoty>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<EqpEntoty>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    rvMaterielList.setVisibility(View.GONE);
                    rvFixtureList.setVisibility(View.GONE);
                    rvMaterielText.setVisibility(View.GONE);
                    rvMaterielLinear.setVisibility(View.GONE);
                    rvFixtureLinear.setVisibility(View.GONE);
                    rvFixtureText.setVisibility(View.GONE);
                    if (rbMaterial.isChecked()){
                        rvMaterielList.setVisibility(View.VISIBLE);
                        rvMaterielText.setVisibility(View.VISIBLE);
                        rvMaterielLinear.setVisibility(View.VISIBLE);
                        mMaterielDataAdapter.setNewData(response.body().getBody().getMKitting().getMLOTLIST());
                    }else {
                        rvFixtureList.setVisibility(View.VISIBLE);
                        rvFixtureLinear.setVisibility(View.VISIBLE);
                        rvFixtureText.setVisibility(View.VISIBLE);
                        mFixtureBeanDataAdapter.setNewData(response.body().getBody().getMKitting().getTOOLLIST());
                    }

                }
            }

            @Override
            public void onError(Response<ResponseBean<EqpEntoty>> response) {
                super.onError(response);
                loadError(response.getException(), "GetEqpKitting");
            }
        });
    }

    private void materielUp() {
        if (etEqpId.getText().toString().equals("")) {
            showToast("请扫描设备编号", false);
            return;
        }
        if (etLotId.getText().toString().equals("")) {
            showToast("请扫描批次编号", false);
            return;
        }
        if (etMTid.getText().toString().equals("")) {
            showToast("请扫描物料/治具编号", false);
            return;
        }
        if (positionDescList.size() == 0) {
            showToast("请先扫描设备获取设备位置信息", false);
            return;
        }
        if (tvPosition.getText().toString().equals("")) {
            showToast("请选择设备位置", false);
            return;
        }
        if (tvType.getText().toString().equals("")) {
            showToast("请扫描获取物料/治具信息", false);
            return;
        }
        JSONObject jsonObject = new JSONObject();
        String desc = "";
        for (int i = 0; i < positionDescList.size(); i++) {
            if (positionDescList.get(i).equals(tvPosition.getText().toString())) {
                desc = positionNameList.get(i);
            }
        }
        try {
            jsonObject.put("EqpID", etEqpId.getText().toString());
            jsonObject.put("LotID", etLotId.getText().toString());
            jsonObject.put("Position", desc);
            jsonObject.put("MTType", rbMaterial.isChecked() ? "M" : "T");
            jsonObject.put("MTID", etMTid.getText().toString());
            jsonObject.put("Type", tvType.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostUtils("mtKittingAttach", "MTKittingAttach", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<Object>>(
                new TypeToken<ResponseBean<Object>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<Object>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("上机成功", true);
                    getEqpKitting(etEqpId.getText().toString());
                }
            }

            @Override
            public void onError(Response<ResponseBean<Object>> response) {
                super.onError(response);
                loadError(response.getException(), "MTKittingAttach");
            }
        });
    }

}
